package java_option.player.javacv.util;

import java.awt.image.BufferedImage;
import java.io.File;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber.Exception;
import org.bytedeco.javacv.Java2DFrameConverter;

import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.WritableImage;

public class JavacvUtil {

	private static Java2DFrameConverter converter = new Java2DFrameConverter();

	/**
	 * 从视频中取图片
	 * 
	 * @param image
	 * @param index
	 * @return
	 */
	public static WritableImage getImage(String videoFile, int index) {
		try {
			FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(new File(videoFile));// new FFmpegFrameGrabber(videoFile);
			grabber.start();
			Frame frame = null;
			int i = 0;
			while (true) {
				frame = grabber.grabKeyFrame();
				if (frame != null && frame.image != null) {
					if (index == i) {
						BufferedImage bufferedImage = converter.getBufferedImage(frame);
						WritableImage javafxImage = SwingFXUtils.toFXImage(bufferedImage, null);
						return javafxImage;
					}
					i++;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
